package com.yonyou.cyxdms.basedata.service.service.series;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.service.constant.BasedataCommonConstants;
import com.yonyou.cyxdms.basedata.service.dto.CarserialDTO;
import com.yonyou.cyxdms.basedata.service.entity.basedata.SystemParamPO;
import com.yonyou.cyxdms.basedata.service.entity.series.SeriesPO;
import com.yonyou.cyxdms.basedata.service.repository.product.VsProductMapper;
import com.yonyou.cyxdms.basedata.service.repository.series.SeriesMapper;
import com.yonyou.cyxdms.basedata.service.service.brand.BrandService;
import com.yonyou.cyxdms.basedata.service.vo.CarparamVO;
import com.yonyou.cyxdms.basedata.service.vo.CarserialDetailsVO;
import com.yonyou.cyxdms.basedata.service.vo.CarserialInfoVO;
import com.yonyou.cyxdms.basedata.service.vo.GroupCarparamVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhangsx
 * @since 2018-09-08
 */
@Service
public class CarSerialServiceImpl extends ServiceImpl<SeriesMapper, SeriesPO> implements CarserialService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(CarSerialServiceImpl.class);
    @Autowired
    public CarserialService carSerialPoService;

    @Autowired
    SeriesMapper carserialMapper;

    @Autowired
    CarserialService carserialService;

    @Autowired
    private VsProductMapper carparamMapper;

    @Autowired
    private BrandService brandService;

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map       <       java.lang.String   ,       java.lang.Object>>     <                                                               java.lang.String                                                               ,                                                               java.lang.Object>>
     * @author zhangsx
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(carserialMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map       <       java.lang.String   ,       java.lang.Object>>
     * @author zhangsx
     * @since 2018/7/22 0022
     */
    @Override
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        return carserialMapper.selectListBySql(queryCondition);
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map       <       java.lang.String   ,       java.lang.Object>>
     * @author zhangsx
     * @since 2018/7/22 0022
     */
    @Override
    public Map<String, Object> getById(Long id) {
        SeriesPO carSerialPo = carserialMapper.selectById(id);
        if (carSerialPo != null) {
            return carSerialPo.toMaps();
        } else {
            return null;
        }
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param carserialDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> insert(CarserialDTO carserialDTO) {
        //对对象进行赋值操作
        SeriesPO carSerialPo = carserialDTO.transDtoToPo(SeriesPO.class);
        //执行插入
        carserialMapper.insert(carSerialPo);
        //返回插入的值
        return carserialMapper.selectById(carSerialPo.getSeriesId()).toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id           主键ID
     * @param carserialDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> update(Long id, CarserialDTO carserialDTO) {
        SeriesPO carSerialPo = carserialMapper.selectById(id);
        //对对象进行赋值操作
        carserialDTO.transDtoToPo(carSerialPo);
        //执行更新
        carserialMapper.updateById(carSerialPo);
        return carSerialPo.toMaps();
    }

    /**
     * 根据车系Id获取车系图片
     *
     * @param serialId
     * @return (non - Javadoc)
     * @author Zhangsx
     * @date 2018年9月8日
     */
    @Override
    public String logoUrl(Long serialId) {
        logger.info("根据车系Id获取车系图片开始---");
        Map<String, Object> map = getById(serialId);
        if (map.get("logo") == null) {
            return null;
        }
        return map.get("logo").toString();
    }

    /**
     * 按条件查询品牌车系信息
     *
     * @param queryCondition 查询条件
     * @return java.util.Map<java.lang.String   ,       java.lang.Object>
     * @author renwd
     * @since 2018/11/26
     */
    @Override
    public Map<String, Object> querySerialByCondition(Map<String, Object> queryCondition) {
        return null;
    }

    /**
     * 根据品牌ID查询车系列表信息
     *
     * @author dengqiang
     * @since 2019/1/2
     */
    @Override
    public List<CarserialInfoVO> queryCarserialInfo(String brandId, String appId, String ownerCode) {
        // 查询系统参数表 - 车系转发URL
        SystemParamPO systemParamPo = brandService.queryRedirectUrl(appId, BasedataCommonConstants.QUERY_SERIES);
        if (systemParamPo != null) {
            String url = systemParamPo.getParamValue();
            String response = brandService.getRedirectResponse(appId, url);
            logger.info("response:-----------------{}", response);
            Map<String, Object> map = JSONUtil.jsonToMap(response);
            return JSONUtil.jsonToList(JSONUtil.objectToJson(map.get("data")), CarserialInfoVO.class);
        } else {
            List<CarserialInfoVO> carserialInfoVOList = carserialMapper.listCarSerial(appId, brandId, ownerCode);
            for (CarserialInfoVO carserialInfoVO : carserialInfoVOList) {
                Double maxOemPrice = carserialInfoVO.getMaxOemPrice();
                Double minOemPrice = carserialInfoVO.getMinOemPrice();
                Double maxDirectivePrice = carserialInfoVO.getMaxDirectivePrice();
                Double minDirectivePrice = carserialInfoVO.getMinDirectivePrice();

                if (maxDirectivePrice != null) {
                    maxOemPrice = maxOemPrice >=  maxDirectivePrice ? maxOemPrice : maxDirectivePrice;
                }
                if (minDirectivePrice != null) {
                    minOemPrice = minOemPrice <= minDirectivePrice ? minOemPrice : minDirectivePrice;
                }

                DecimalFormat df = new DecimalFormat(".##");
                carserialInfoVO.setMaxPrice(Double.valueOf(df.format(maxOemPrice / 10000)));
                carserialInfoVO.setMinPrice(Double.valueOf(df.format(minOemPrice / 10000)));
            }
            return carserialInfoVOList;
        }
    }

    /**
     * 根据车系ID查询车系详情
     *
     * @author dengqiang
     * @since 2019/1/2
     */
    @Override
    public CarserialDetailsVO queryCarserialDetails(Long carserialId, String appId) {
        //根据车系id获取车系
        LambdaQueryWrapper<SeriesPO> queryWrapper = new QueryWrapper<SeriesPO>().lambda();
        queryWrapper.eq(SeriesPO::getSeriesId, carserialId);
        queryWrapper.eq(SeriesPO::getAppId, appId);
        SeriesPO carserial = carSerialPoService.getOne(queryWrapper);
        //创建车系详情对象
        CarserialDetailsVO carserialDetailsVO = new CarserialDetailsVO();
        //设置车系基本信息
        carserialDetailsVO.setCarserialId(carserial.getSeriesId());
        carserialDetailsVO.setName(carserial.getSeriesName());
        carserialDetailsVO.setMinPrice(carserial.getMinPrice());
        carserialDetailsVO.setMaxPrice(carserial.getMaxPrice());
        carserialDetailsVO.setCarserialPic(carserial.getCarserialPic());
        carserialDetailsVO.setIntroduction(carserial.getIntroduction());
        //根据车系ID获取车型信息列表
        List<CarparamVO> carParamVos = carparamMapper.queryCarparamList(carserialId);
        doCarserialDetails(carParamVos,carserialDetailsVO);
        return carserialDetailsVO;
    }

    @Override
    public void doCarserialDetails(List<CarparamVO> carParamVos,CarserialDetailsVO carserialDetailsVO){
        Map<String, List<CarparamVO>> carparamMap = new LinkedHashMap<>();
        List<String> disPlacementS = new ArrayList<>();
        for (CarparamVO carparamVO : carParamVos) {
            if (!disPlacementS.contains(carparamVO.getDisPlacement())) {
                disPlacementS.add(carparamVO.getDisPlacement());
            }
        }
        for (String disPlacement : disPlacementS) {
            List<CarparamVO> carparamlist = new ArrayList<>();
            for (CarparamVO carparamVO : carParamVos) {
                if (disPlacement.equals(carparamVO.getDisPlacement())) {
                    carparamlist.add(carparamVO);
                }
            }
            carparamMap.put(disPlacement, carparamlist);
        }

        List<GroupCarparamVO> carParamVOList = new LinkedList<>();
        for (Map.Entry<String, List<CarparamVO>> entry : carparamMap.entrySet()) {
            GroupCarparamVO groupCarParamVO = new GroupCarparamVO();
            groupCarParamVO.setName(entry.getKey());
            groupCarParamVO.setList(entry.getValue());
            carParamVOList.add(groupCarParamVO);
        }
        carserialDetailsVO.setCarparamList(carParamVOList);
    }
}
